/******************************************************************************

    Simple Authentication and Authorisation System (SAAS)

    misc.c

    Copyright (C) 2011  Josh Goes


    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    If you require a mailing address for this software, please send your
    mail to the following address:
        SAAS
        GPO Box 2973
        BRISBANE QLD 4001
        AUSTRALIA

******************************************************************************/


#include "saas-build.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>

#include <stdint.h>


uint32_t  gen_trans_id( void )
{
	uint32_t  out;
	gen_rand_data( &out , sizeof( out ) );
	return out;
}


uint32_t  gen_rand( uint32_t max )
{
	return ( gen_trans_id() % max );
}


void  gen_rand_data( void *buf , uint32_t len )
{
	int f = open( SAAS_RANDOM_FILE , O_RDONLY );
	read( f , buf , len );
	close( f );
}


void  trim( char **str )
{
	// a variable into which values are dropped and not read to shut up GCC.
	char unused;

	// trim the left.
	while ( **str == ' ' )
		unused = *(*str)++;

	char *rev = *str + strlen( *str ) - 1;

	// trim the right.
	while ( *rev == ' ' )
	{
		*rev = '\0';
		rev--;
	}
}


uint32_t u32tonet( uint32_t i )
{
#ifdef SAAS_ENDIAN_LITTLE
	return htonl( i );
#else
	return i;
#endif
}


uint32_t u32fromnet( uint32_t i )
{
#ifdef SAAS_ENDIAN_LITTLE
	return ntohl( i );
#else
	return i;
#endif
}


uint16_t u16tonet( uint16_t i )
{
#ifdef SAAS_ENDIAN_LITTLE
	return htons( i );
#else
	return i;
#endif
}


uint16_t u16fromnet( uint16_t i )
{
#ifdef SAAS_ENDIAN_LITTLE
	return ntohs( i );
#else
	return i;
#endif
}





